package com.tang.common.utils;

import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author tang jun liang
 * @Date 2023/10/7 08:21
 */
public class ReflectUtil {


    @SneakyThrows
    public static Object getFileValue(Object object, String filed){
        Class clazz = object.getClass();
        Field declaredField = clazz.getDeclaredField(filed);
        declaredField.setAccessible(true);
        Object value = declaredField.get(object);
        if (value instanceof String){
            return value;
        }
        return JSON.toJSONString(value);
    }

    @SneakyThrows
    public static String getEnumValue(Object value, Class clazz) {
        Method getValue = clazz.getDeclaredMethod("getValue");
        return  getValue.invoke(value).toString();
    }


    @SneakyThrows
    public static Object getEnumValue(String value, Class clazz) {
        Object[] enumConstants = clazz.getEnumConstants();
        Method getValue = clazz.getDeclaredMethod("getValue");
        for (Object item: enumConstants){
            Integer itemValue = (Integer) getValue.invoke(item);
            if (itemValue.equals(Integer.valueOf(value))){
                return item;
            }
        }
        return null;
    }

}
